package com.hzwq.demo.Login.controller;

import com.hzwq.common.JsonResult;
import com.hzwq.demo.Login.bo.SdteUser;
import com.hzwq.demo.Login.service.ISdteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
public class LoginController {

    private static Logger log = Logger.getLogger(LoginController.class);

    @Autowired
    private ISdteUserService iSdteUserService;

    @RequestMapping("/loginPage")
    public String loginPage(){

        return "login/login";
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest request){
        request.getSession().invalidate();
        return "login/login";
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JsonResult<SdteUser> login(SdteUser sdteUser){
        SdteUser su = iSdteUserService.queryUser(sdteUser.getLoginName(), sdteUser.getLoginPwd());
        JsonResult result = new JsonResult();
        if(su!=null){
            result.setCode("1");
            ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = sra.getRequest();;
            result.setData(su);
            HttpSession session =  request.getSession();
            session.setAttribute("su",su);
            session.setMaxInactiveInterval(180);//180秒
            result.setMsg("登陆成功");
        }else{
            result.setCode("0");
            result.setData(su);
            result.setMsg("登陆失败！");
        }
        return result;
    }

    @RequestMapping("/index")
    public ModelAndView  index(long userId){
        SdteUser user = iSdteUserService.queryUserById(userId);
        ModelAndView mav = new ModelAndView();
        mav.addObject("userName", user.getUserName());
        mav.addObject("userId", user.getUserId());
        mav.setViewName("index");
        return mav;
    }


}
